package com.telit.common.util;

import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * Create by Chencf on 2023/01/17
 */
public class CommonUtil {

    /**
     * 将id字符串转换为集合
     */
    public static Set<Integer> convertNumberSet(String ids) {
        Set<Integer> idList = new HashSet<>();
        if (StringUtils.isNotBlank(ids)) {
            String[] roleArr = ids.split("[,\\.，。 、]");
            for (String roleId : roleArr) {
                if (StringUtils.isBlank(roleId)) {
                    continue;
                }
                try {
                    idList.add(Integer.parseInt(roleId));
                } catch (NumberFormatException e) {
                    // id异常，掠过
                }
            }
        }
        return idList;
    }

    public static List<String> convertStringList(String ids) {
        List<String> idList = new ArrayList<>();
        if (StringUtils.isNotBlank(ids)) {
            String[] roleArr = ids.split("[,\\.，。 、]");
            for (String roleId : roleArr) {
                if (StringUtils.isBlank(roleId)) {
                    continue;
                }
                idList.add(roleId);
            }
        }
        return idList;
    }


    /**
     * 将数字转为指定长度的字符串，长度不够前边补0
     */
    public static String formatNumber(int number, int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append("0");
        }
        return sb.append(number).substring(sb.length() - length);
    }




    /**
     * Map 转 UrlPrams (a=11&b=22&c=33)
     */
    public static String map2ParamString(Map<String, Object> map) {
        if (map==null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (String key : map.keySet()) {
            sb.append(key)
                    .append("=")
                    .append(Objects.toString(map.get(key), ""))
                    .append("&");
        }
        if (sb.length()>0) {
            sb.setLength(sb.length() - 1);
        }
        return sb.toString();
    }
}

